package com.tangyee.home_exercise_diet.fragment;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.tangyee.home_blood_center.utils.DateUtil;
import com.tangyee.R;
import com.tangyee.home_blood_center.utils.DateUtil;
import com.tangyee.home_blood_center.utils.DensityUtils;
import com.tangyee.home_exercise_diet.activities.AddFoodOrExerciseActivity;
import com.tangyee.home_exercise_diet.beans.FoodOrExercise;
import com.tangyee.home_exercise_diet.beans.FoodOrExerciseList;
import com.tangyee.home_exercise_diet.beans.TypeEnum;
import com.tangyee.home_exercise_diet.dao.FoodOrExerciseHolder;
import com.tangyee.home_exercise_diet.view.CommonPopupWindow;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import yanzhikai.ruler.BooheeRuler;
import yanzhikai.ruler.KgNumberLayout;

public class FoodOrExerciseListFragment extends Fragment {

    private static final String TYPE = "type";
    private static final String DATE = "date";
    private static final String TYPE_ENUM = "typeEnum";

    // 日期
    private String date;
    // 类型：常用、收藏
    private String type;
    // 记录的类型：早餐、早上加餐。。。
    private String typeEnum;

    private RecyclerView mRecyclerView;
    private MyAdapter adapter;
    // view Pool （用于recycleview性能优化）
    private RecyclerView.RecycledViewPool mPool = new RecyclerView.RecycledViewPool();

    // 所有的食物/运动
    private List<FoodOrExercise> mFoodOrExercises;

    // 别人家的弹窗封装类
    private CommonPopupWindow window;
    private View activityPopup;

    // 别人家的控件之--尺子选择器
    private BooheeRuler br_top_head;
    private KgNumberLayout knl_top_head;

    // 弹窗的取消、确定、收藏 按钮
    private TextView cancel;
    private TextView sure;
    private ImageView collect;

    // 被点击itemView的下标
    private int clickedIndex;
    // 别点击的运动/食物记录
    private FoodOrExercise clickedFoodOrExercise;
    // 已选的记录List
    private List<FoodOrExercise> preSelectedList;
    // 这次选择的记录List
    private List<FoodOrExercise> selectedList;

    // 收藏项的List
    private List<FoodOrExercise> collects;

    // 初始化弹窗
    private void initPopupWindow() {
        // get the height of screen
        DisplayMetrics metrics=new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int screenHeight=metrics.heightPixels;
        // create popup window
        window=new CommonPopupWindow(getActivity(), R.layout.exercise_and_diet_item_popup_view, ViewGroup.LayoutParams.MATCH_PARENT, (int) (screenHeight*0.55)) {

            /**
             * 初始化弹窗界面
             */
            @Override
            protected void initView() {
                View view=getContentView();

                br_top_head = view.findViewById(R.id.br_top_head);
                knl_top_head = view.findViewById(R.id.knl_top_head);
                knl_top_head.bindRuler(br_top_head);

                cancel = view.findViewById(R.id.cancel_tv);
                sure = view.findViewById(R.id.sure_tv);

                collect = view.findViewById(R.id.collect);

            }

            /**
             * 初始化弹窗中每一个控件的事件
             */
            @Override
            protected void initEvent() {
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        window.getPopupWindow().dismiss();
                    }
                });
                sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        clickedFoodOrExercise.setAmount(knl_top_head.getScale()/10);

                        boolean flag = true;
                        preSelectedList = ((AddFoodOrExerciseActivity)getActivity()).getPreSelectedList();
                        selectedList = ((AddFoodOrExerciseActivity)getActivity()).getSelectedList();
                        for (int i = 0; i < preSelectedList.size(); i ++){
                            FoodOrExercise foodOrExercise = preSelectedList.get(i);
                            if (foodOrExercise.getName().equals(clickedFoodOrExercise.getName())) {
                                foodOrExercise.setAmount(clickedFoodOrExercise.getAmount());
                                ((AddFoodOrExerciseActivity)getActivity()).updateNum(true);
                                flag = false;
                                break;
                            }
                        }
                        for (int i = 0; i < selectedList.size(); i ++){
                            FoodOrExercise foodOrExercise = selectedList.get(i);
                            if (foodOrExercise.getName().equals(clickedFoodOrExercise.getName())) {
                                foodOrExercise.setAmount(clickedFoodOrExercise.getAmount());
                                flag = false;
                                break;
                            }
                        }
                        if (flag){
                            ((AddFoodOrExerciseActivity)getActivity()).updateNum(true);
                            selectedList.add(clickedFoodOrExercise);
                        }

                        window.getPopupWindow().dismiss();
                    }
                });

                collect.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        FoodOrExercise c = FoodOrExerciseList.getCollected(clickedFoodOrExercise);
                        if (isCollected(c)){
                            try {
                                ((ImageView)view).setImageResource(R.drawable.non_collect);
                                FoodOrExerciseHolder.get(getContext().getApplicationContext()).deleteRecord(DateUtil.parseDate("1111-11-11"), c.getType(),c.getName());
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            ((ImageView)view).setImageResource(R.drawable.collect);
                            FoodOrExerciseHolder.get(getContext().getApplicationContext()).insertRecord(c);
                        }
                        setUserVisibleHint(true);
                    }
                });

            }

            /**
             * 初始化PopupWindow弹窗
             */
            @Override
            protected void initWindow() {
                super.initWindow();
                PopupWindow instance=getPopupWindow();
                instance.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp=getActivity().getWindow().getAttributes();
                        lp.alpha=1.0f;
                        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                        getActivity().getWindow().setAttributes(lp);
                        collects = FoodOrExerciseHolder.get(getActivity().getApplicationContext()).getListByDateAndType("1111-11-11", typeEnum.equals(TypeEnum.EXERCISE.name())?TypeEnum.COLLECT2.name():TypeEnum.COLLECT1.name());
                    }
                });
            }
        };
    }

    /**
     * 获得本类实例
     * @param date
     * @param typeEnum
     * @param type
     * @return
     */
    public static FoodOrExerciseListFragment newInstance(String date,String typeEnum, String type) {
        FoodOrExerciseListFragment fragment = new FoodOrExerciseListFragment();
        Bundle args = new Bundle();
        args.putString(TYPE, type);
        args.putString(DATE, date);
        args.putString(TYPE_ENUM, typeEnum);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 取出传递进来的参数
        if (getArguments() != null) {
            type = getArguments().getString(TYPE);
            date = getArguments().getString(DATE);
            typeEnum = getArguments().getString(TYPE_ENUM);
        }
        initPopupWindow();
        activityPopup=getActivity().findViewById(R.id.add_food_activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.exercise_and_diet_fragment_food_exercise_list, container, false);

        this.mRecyclerView = view.findViewById(R.id.food_list);
        mPool.setMaxRecycledViews(0, 15);
        mRecyclerView.setRecycledViewPool(mPool);
        mRecyclerView.setHasFixedSize(true);

        // 食物或运动List
        if (this.type.equals("常见")) {
            if (this.typeEnum.equals(TypeEnum.EXERCISE.name()))
                this.mFoodOrExercises = FoodOrExerciseList.getExerciseList();
            else
                this.mFoodOrExercises = FoodOrExerciseList.getFoodList();
        }
        else {
            updateCollects();
            this.mFoodOrExercises = collects;
        }

        this.mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter =  new MyAdapter(getContext(), mFoodOrExercises);
        this.mRecyclerView.setAdapter(adapter);

        return view;
    }

    /**
     * 更新收藏LIst
     */
    private void updateCollects() {
        collects = FoodOrExerciseHolder.get(getActivity().getApplicationContext()).getListByDateAndType("1111-11-11", typeEnum.equals(TypeEnum.EXERCISE.name())?TypeEnum.COLLECT2.name():TypeEnum.COLLECT1.name());
        for (int i = 0; i < collects.size(); i++){
            collects.get(i).setType(TypeEnum.valueOf(typeEnum));
        }
    }

    /**
     * 判断是否被收藏
     * @param foodOrExercise
     * @return
     */
    private boolean isCollected(FoodOrExercise foodOrExercise){
        for(FoodOrExercise f : collects){
            if (f.getName().equals(foodOrExercise.getName())){
                return true;
            }
        }
        return false;
    }

    /**
     * 自定义的RecyclerView.Adapter
     */
    class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {

        Context mContext;
        List<FoodOrExercise> mFoodOrExerciseList;

        public MyAdapter(Context context, List<FoodOrExercise> foodOrExerciseList) {
            mContext = context;
            mFoodOrExerciseList = foodOrExerciseList;
        }

        public void setFoodOrExerciseList(List<FoodOrExercise> list){
            this.mFoodOrExerciseList = list;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View view = getLayoutInflater().inflate(R.layout.exercise_and_diet_recyclerview_item, viewGroup, false);
            view.setOnClickListener(this);
            MyHolder myHolder = new MyHolder(view);
            return myHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int i) {

            FoodOrExercise foodOrExercise = mFoodOrExerciseList.get(i);
            ((MyHolder)holder).item_name.setText(foodOrExercise.getName());
            ((MyHolder)holder).item_calorie.setText(foodOrExercise.getPerUnitCalorie() + " " + foodOrExercise.getUnit());
            ((MyHolder)holder).item_img.setImageResource(foodOrExercise.getImg());

            ((MyHolder)holder).itemView.setTag(i);
        }

        @Override
        public int getItemCount() {
            if (mFoodOrExerciseList == null)
                return 0;
            return mFoodOrExerciseList.size();
        }

        @Override
        public void onClick(View view) {
            PopupWindow win=window.getPopupWindow();
            win.setAnimationStyle(R.style.animTranslate);

            // java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
            // 子view已经有了一个父view
//            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DensityUtils.dp2px(getContext(), 60));
//            LinearLayout linearLayout = ((LinearLayout)window.getContentView()).findViewById(R.id.popup_view);
//            linearLayout.removeView(view);
//            linearLayout.addView(view, params);

            LinearLayout linearLayout = (LinearLayout) window.getContentView();
            clickedIndex = (Integer) view.getTag();
            clickedFoodOrExercise = this.mFoodOrExerciseList.get(clickedIndex);
            ((ImageView)linearLayout.findViewById(R.id.food_img)).setImageResource(clickedFoodOrExercise.getImg());
            ((TextView)linearLayout.findViewById(R.id.food_name)).setText(clickedFoodOrExercise.getName());
            ((TextView)linearLayout.findViewById(R.id.food_calorie)).setText(clickedFoodOrExercise.getPerUnitCalorie() + clickedFoodOrExercise.getUnit());

            if (isCollected(clickedFoodOrExercise)){
                ((ImageView)linearLayout.findViewById(R.id.collect)).setImageResource(R.drawable.collect);
            } else {
                ((ImageView)linearLayout.findViewById(R.id.collect)).setImageResource(R.drawable.non_collect);
            }

            br_top_head.setCurrentScale((float) (clickedFoodOrExercise.getAmount() * 10));
            br_top_head.refreshRuler();

            String unit = clickedFoodOrExercise.getUnit();
            unit = unit.substring(unit.lastIndexOf('0')+1);
            knl_top_head.setUnitText(unit);

            window.showAtLocation(activityPopup, Gravity.BOTTOM, 0, 0);
            WindowManager.LayoutParams lp=getActivity().getWindow().getAttributes();
            lp.alpha=0.3f;
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            getActivity().getWindow().setAttributes(lp);
        }

    }

    /**
     * 自定义的RecyclerView.ViewHolder
     */
    class MyHolder extends RecyclerView.ViewHolder {

        TextView item_name;
        TextView item_calorie;
        ImageView item_img;

        public MyHolder(@NonNull View itemView) {
            super(itemView);
            item_name = itemView.findViewById(R.id.food_name);
            item_calorie = itemView.findViewById(R.id.food_calorie);
            item_img = itemView.findViewById(R.id.food_img);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        this.collects = FoodOrExerciseHolder.get(getActivity().getApplicationContext()).getListByDateAndType("1111-11-11", typeEnum.equals(TypeEnum.EXERCISE.name())?TypeEnum.COLLECT2.name():TypeEnum.COLLECT1.name());
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (type != null) {
            updateCollects();
        if (type.equals("收藏")) {
                mFoodOrExercises = collects;

                adapter.setFoodOrExerciseList(mFoodOrExercises);
                adapter.notifyDataSetChanged();
            }

        }
    }
}
